package type.fragment;

import static android.content.ContentValues.TAG;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import home.fragment.HomeFragment;

import com.example.xfengshopping.MainActivity;
import com.example.xfengshopping.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import user.fragment.AddressManagementActivity;
import user.fragment.CityPickerActivity;
import type.fragment.Adapter.CategoryListAdapter;
import type.fragment.Adapter.SubcategoryRecyclerAdapter;
import type.fragment.Adapter.ThirdLevelAdapter;
import type.fragment.Adapter.CategoryListAdapter.OnCategorySelectedListener;

public class TypeFragment extends Fragment implements OnCategorySelectedListener, SubcategoryRecyclerAdapter.OnThirdLevelClickListener {
    private View rootView;
    private ListView lvCategory;
    private RecyclerView rvSubcategory;
    private TextView tvTitle;
    private ImageView ivBack; // 返回按钮
    private ImageView ivMenu; // 新增：右上角菜单图标
    private CategoryListAdapter categoryAdapter;
    private SubcategoryRecyclerAdapter subcategoryAdapter;
    private List<CategoryModel> categoryList = new ArrayList<>();
    private boolean isDataLoaded = false;
    private int selectedPosition = 0;

    // 定义回调接口，用于通知 Activity 返回首页
    public interface OnBackToHomeListener {
        void onBackToHome();
    }

    private OnBackToHomeListener mListener;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                updateUI();
            } else if (msg.what == 0) {
                showToast("数据加载失败");
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_type, container, false);
            initViews();
            setupBackButton();
            setupMenuButton(); // 新增：设置菜单按钮点击事件
        }
        return rootView;
    }


    private void initViews() {
        ivBack = rootView.findViewById(R.id.iv_back);
        lvCategory = rootView.findViewById(R.id.lv_category);
        ivMenu = rootView.findViewById(R.id.iv_menu); // 新增：获取右上角图标
        rvSubcategory = rootView.findViewById(R.id.rv_subcategory);
        tvTitle = rootView.findViewById(R.id.tv_title);
        lvCategory.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        rvSubcategory.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

    private void setupBackButton() {
        ivBack.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.onBackToHome(); // 触发回调，通知 Activity 返回首页
            }
        });
    }
    private void setupMenuButton() {
        ivMenu.setOnClickListener(new View.OnClickListener() { // 新增：点击事件
            @Override
            public void onClick(View v) {
                // 跳转到CityPickerActivity
                Intent intent = new Intent(getActivity(), AddressManagementActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        // 绑定回调接口
        if (context instanceof OnBackToHomeListener) {
            mListener = (OnBackToHomeListener) context;
        } else {
            throw new RuntimeException(context.toString() + " must implement OnBackToHomeListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null; // 避免内存泄漏
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            selectedPosition = savedInstanceState.getInt("selectedPosition", 0);
        }
        if (!isDataLoaded) {
            initData();
            isDataLoaded = true;
        } else {
            updateUI();
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("selectedPosition", selectedPosition);
    }

    public void initData() {
        new Thread(this::fetchCategoryData).start();
    }

    private void fetchCategoryData() {
        try {
            URL url = new URL("http://47.99.134.126:28019/api/v1/categories");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String response = readInputStream(conn.getInputStream());
                parseCategoryData(response);
            } else {
                handler.sendEmptyMessage(0);
            }
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(0);
        }
    }

    private String readInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        return byteArrayOutputStream.toString();
    }

    private void parseCategoryData(String response) {
        categoryList.clear();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray dataArray = jsonObject.optJSONArray("data");
            if (dataArray == null || dataArray.length() == 0) {
                handler.sendEmptyMessage(0);
                return;
            }

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject categoryObj = dataArray.getJSONObject(i);
                CategoryModel category = new CategoryModel();
                category.setCategoryId(categoryObj.optInt("categoryId"));
                category.setCategoryName(categoryObj.optString("categoryName"));

                JSONArray secondLevelArray = categoryObj.optJSONArray("secondLevelCategoryVOS");
                List<SecondLevelCategory> secondLevelList = new ArrayList<>();
                if (secondLevelArray != null) {
                    for (int j = 0; j < secondLevelArray.length(); j++) {
                        JSONObject secondObj = secondLevelArray.getJSONObject(j);
                        SecondLevelCategory secondCategory = new SecondLevelCategory();
                        secondCategory.setCategoryId(secondObj.optInt("categoryId"));
                        secondCategory.setParentId(secondObj.optInt("parentId"));
                        secondCategory.setCategoryName(secondObj.optString("categoryName"));

                        JSONArray thirdLevelArray = secondObj.optJSONArray("thirdLevelCategoryVOS");
                        List<ThirdLevelCategory> thirdLevelList = new ArrayList<>();
                        if (thirdLevelArray != null) {
                            for (int k = 0; k < thirdLevelArray.length(); k++) {
                                JSONObject thirdObj = thirdLevelArray.getJSONObject(k);
                                ThirdLevelCategory thirdCategory = new ThirdLevelCategory();
                                thirdCategory.setCategoryId(thirdObj.optInt("categoryId"));
                                thirdCategory.setCategoryName(thirdObj.optString("categoryName"));
                                thirdCategory.setIconUrl(thirdObj.optString("iconUrl", ""));
                                thirdLevelList.add(thirdCategory);
                            }
                        }
                        secondCategory.setThirdLevelCategoryVOS(thirdLevelList);
                        secondLevelList.add(secondCategory);
                    }
                }
                category.setSecondLevelCategoryVOS(secondLevelList);
                categoryList.add(category);
            }

            handler.sendEmptyMessage(1);
        } catch (JSONException e) {
            e.printStackTrace();
            handler.sendEmptyMessage(0);
        }
    }

    private void updateUI() {
        if (categoryList.isEmpty()) {
            showToast("分类数据为空");
            return;
        }

        if (categoryAdapter == null) {
            categoryAdapter = new CategoryListAdapter(getActivity(), categoryList, this);
            lvCategory.setAdapter(categoryAdapter);
        }
        categoryAdapter.setSelectedPosition(selectedPosition); // 更新选中位置

        if (subcategoryAdapter == null) {
            subcategoryAdapter = new SubcategoryRecyclerAdapter(getActivity(), categoryList.get(selectedPosition).getSecondLevelCategoryVOS());
            subcategoryAdapter.setOnThirdLevelClickListener(this);
            rvSubcategory.setAdapter(subcategoryAdapter);
        } else {
            subcategoryAdapter.updateData(categoryList.get(selectedPosition).getSecondLevelCategoryVOS());
        }

        tvTitle.setText(categoryList.get(selectedPosition).getCategoryName());
    }

    private void showToast(String message) {
        Activity activity = getActivity();
        if (activity != null) {
            activity.runOnUiThread(() -> Toast.makeText(activity, message, Toast.LENGTH_SHORT).show());
        }
    }

    @Override
    public void onCategorySelected(int position) {
        selectedPosition = position;
        categoryAdapter.setSelectedPosition(position); // 更新适配器选中状态

        CategoryModel selectedCategory = categoryList.get(position);
        tvTitle.setText(selectedCategory.getCategoryName());

        if (subcategoryAdapter != null) {
            subcategoryAdapter.updateData(selectedCategory.getSecondLevelCategoryVOS());
        }
    }

    @Override
    public void onThirdLevelClick(ThirdLevelCategory category) {
        showToast("点击：" + category.getCategoryName());
    }
}